package com.saascloud.encryption;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.cloud.nacos.configdata.NacosConfigDataLocationResolver;
import org.apache.commons.logging.Log;
import org.springframework.boot.context.config.ConfigDataLocationResolverContext;

import java.nio.charset.StandardCharsets;

public class NacosDecryptionConfiguration extends NacosConfigDataLocationResolver {
    public NacosDecryptionConfiguration(Log log) {
        super(log);
    }

    @Override
//    @Bean
    protected NacosConfigProperties loadProperties(ConfigDataLocationResolverContext context) {
        NacosConfigProperties nacosConfigProperties = super.loadProperties(context);
        try {
            SymmetricCrypto decPassword = new SymmetricCrypto(SymmetricAlgorithm.AES, nacosConfigProperties.getPassword().substring(4, 20).getBytes(StandardCharsets.UTF_8));
            String desPassword = decPassword.decryptStr(nacosConfigProperties.getPassword().substring(20, nacosConfigProperties.getPassword().length() - 1), CharsetUtil.CHARSET_UTF_8);
            nacosConfigProperties.setPassword(desPassword);
        } catch (Exception ignored) {

        }
        return nacosConfigProperties;
    }

    @Override
    public int getOrder() {
        return -2;
    }
}
